from django.shortcuts import render

# Create your views here.
from django.views import View
from rest_framework import status
from rest_framework.generics import CreateAPIView, DestroyAPIView, RetrieveDestroyAPIView
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.exceptions import OAuthQQAPIError
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer, DeleteOAuthQQSerializer
from oauth.utils import OAuthQQ


class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    """
    def get(self, request):
        """
        提供用于qq登录的url
        """
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_login_url()
        return Response({'login_url': login_url})


class QQAuthUserView(CreateAPIView):
    """
    QQ登录的用户  ?code=xxxx
    """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        # 获取code
        code = request.query_params.get('code')

        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        oauth_qq = OAuthQQ()
        try:
            # 凭借code 获取access_token
            access_token = oauth_qq.get_access_token(code)

            # 凭借access_token获取 openid
            openid = oauth_qq.get_openid(access_token)
        except OAuthQQAPIError:
            return Response({'message': '访问QQ接口异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 根据openid查询数据库OAuthQQUser  判断数据是否存在
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果数据不存在，处理openid 并返回
            access_token = oauth_qq.generate_bind_user_access_token(openid)
            return Response({'access_token': access_token})

        else:
            # 如果数据存在，表示用户已经绑定过身份， 签发JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            user = oauth_qq_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        return response


class QQAuthView(RetrieveDestroyAPIView):

    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        queryset = OAuthQQUser.objects.filter(user_id=pk)
        queryset.delete()
        return Response({'message': "ok"})

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        queryset = OAuthQQUser.objects.filter(user_id=pk)
        data = queryset.count()
        return Response({'count': data})
